package com.gasolinator.a.app.helper;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * Created by IntelliJ IDEA.
 * User: fjhidalgo
 * Date: 18/12/11
 * Time: 20:18
 * To change this template use File | Settings | File Templates.
 */
public class JsonUtils {

    public static String getUpdatedFavoritesJson(Integer gasStationId, boolean active, String favs) throws JSONException {
        JSONArray jsonArray = new JSONArray(favs);
        int isGasIdInFavorites= isGasIdInFavorites(gasStationId, favs);
        String jsonArrayString = favs;
        if (active&&isGasIdInFavorites==0) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("GasolineraId",gasStationId+"");
            jsonArray.put(jsonObject);
            jsonArrayString = jsonArray.toString();
        } else if (!active&&isGasIdInFavorites!=0) {
            JSONArray jsonArraytemp = new JSONArray("[]");
            for (int x=0;x<jsonArray.length();x++) {
                JSONObject jsonObject = jsonArray.getJSONObject(x);
                if ((x+1)!=isGasIdInFavorites) jsonArraytemp.put(jsonObject);
            }
            jsonArrayString = jsonArraytemp.toString();
        }
        return jsonArrayString;
    }

    public static int isGasIdInFavorites(Integer gasStationId, String favs) throws JSONException {

        int isGasIdInFavorites = 0;
        JSONArray jsonArray = new JSONArray(favs);
        for (int x=0;x<jsonArray.length();x++) {
            JSONObject jsonObject = jsonArray.getJSONObject(x);
            int id = jsonObject.getInt("GasolineraId");
            if (id==gasStationId) isGasIdInFavorites=x+1;
        }
        return isGasIdInFavorites;
    }
}
